/**
 * 
 */
package praktikumid.w06.p3;

import java.io.IOException;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.Document;

/**
 * @author Aleksandr
 *
 */
public class XMLParser {

	/**
	 * @param args arguments
	 */
	public static void main(String[] args) {

		/*
		 * Parsers:
		 * DOM - Document Object Model
		 * SAX - 
		 * JDom - 
		 */
		
	System.out.println("Query: " + composePanoramioQuery("Tallinn"));
		
	}
	
	private static String composePanoramioQuery(String city) {
		String googleQuery = "http://maps.googleapis.com/maps/api/geocode/xml?" 
			+ "address=" + city + "&sensor=false";

		try {
			SAXBuilder builder = new SAXBuilder();
			Document document = (Document) builder.build(googleQuery);
			Element rootNode = document.getRootElement();
			
			/* 
			 * The following XPath
			 * may throw NullPointerException
			 * which should be handled properly
			 */
			Element bounds = rootNode.getChild("result")
				.getChild("geometry").getChild("bounds");
			

			Element sw = bounds.getChild("southwest");
			Element ne = bounds.getChild("northeast");
			if (sw == null || ne == null) {
				System.err.println("Malformed input");
				System.exit(0);	
			}
			String minx = sw.getChildText("lng");
			String miny = sw.getChildText("lat");
			String maxx = ne.getChildText("lng");
			String maxy = ne.getChildText("lat");
			System.out.println("Minx: " + minx);
			System.out.println("MinY: " + miny);
			System.out.println("MaxX: " + maxx);
			System.out.println("MaxY: " + maxy);
			
			String panoramioQuery = "http://www.panoramio.com/map/" 
				+ "get_panoramas.php?set=public&from=0&to=20&"
				+ "minx=" + minx + "&miny=" + miny + "&maxx=" + maxx 
				+ "maxy=" + maxy + "&size=medium&mapfilter=true";
			return panoramioQuery;
		} catch (JDOMException | IOException e) {
			//e.printStackTrace();
			System.out.println("Malformed input");
			return null;
		} catch (NullPointerException e) {
			System.out.println("XPath: GeocodeResponse/result/geometry/bounds does not exist.");
			return null;
		}
	}
}
